
import React,{Component} from 'react';
import {Button, Checkbox, FormControl, Icon, Select, Table, Popconfirm, Modal, Upload} from 'tinper-bee';
import {getosssignForPost, getPicUrlByOSS} from '../WorkQuality/workquality.config';
import {vendorsWarning  as warning, vendorsDanger as danger, vendorsGetUrlParam as getUrlParam, vendorsTrimStr as trimStr, vendorsGetTId} from '../../utils/config'
import './UploadPictures.less';
import uuid4 from "uuid/v4";
import { isUndefined } from 'util';
import axios from "axios";
export default class UploadPictures extends Component{
    constructor(props){
        super(props);
        this.state = {
            currPicutreIndex : 0,//暂时设置删除后显示第一个
            fileInfoArr :[],
            defaultData : [...this.props.defaultDataForPic],
        }
    }
    componentWillMount(){
        
        if(this.props.showModal){
            if(this.props.fileInfoArr.length > 0){//编辑态
                this.setState({
                    fileInfoArr : [... this.props.fileInfoArr],
                    currPicutreIndex : 0
                }, ()=>{
                    if(this.state.fileInfoArr.length>0){
                        document.getElementById(`name${this.state.currPicutreIndex}`).style.color = "#2C7EDC"
                    }
                })
            }else{//浏览太
                this.setState({
                    fileInfoArr : this.props.defaultDataForPic[this.props.currentRowIndex] ?[...this.props.defaultDataForPic[this.props.currentRowIndex]] : [],
                    currPicutreIndex : 0
                }, ()=>{
                    if(this.state.fileInfoArr.length>0){
                        document.getElementById(`name${this.state.currPicutreIndex}`).style.color = "#2C7EDC"
                    }
                })
            }
         }
    }

    componentWillReceiveProps(nextProps){
        if(nextProps.showModal){
           if(nextProps.fileInfoArr.length > 0){//有获取OSS的http地址的图片
            this.setState({
                fileInfoArr : [...nextProps.fileInfoArr],
                currPicutreIndex : 0
            }, ()=>{
                if(this.state.fileInfoArr.length>0){
                    document.getElementById(`name${this.state.currPicutreIndex}`).style.color = "#2C7EDC"
                }
            })
           }else{//浏览，查看。代表本行已经有了图片
                this.setState({
                    fileInfoArr : nextProps.defaultDataForPic[nextProps.currentRowIndex] ?[...nextProps.defaultDataForPic[nextProps.currentRowIndex]] : [],
                    currPicutreIndex : 0
                }, ()=>{
                    if(this.state.fileInfoArr.length>0){
                        document.getElementById(`name${this.state.currPicutreIndex}`).style.color = "#2C7EDC"
                    }
                })
            
            }
        }
    }

    handlePicWithOSS =(e)=>{
        let _this = this;
        if(_this.state.fileInfoArr.length >= 5){
            warning({ 'text': "最多上传5张图片" }) ;
            return;
        }

        if(e.target.files[0].size - 5*1024*1024 > 0 ){
            warning({ 'text': "图片大小不得超过5M" }) ;
            return;
        }
        //存入file对象。便于上传阿里OSS时用
        let fileInfoArr =  [..._this.state.fileInfoArr];
        fileInfoArr[ _this.state.fileInfoArr.length] = {'file' : e.target.files[0]};

        let  reader = new FileReader();
        reader.readAsDataURL( fileInfoArr[_this.state.fileInfoArr.length].file );
        //本地成功后在获取对象信息
        reader.onload  = function(e) { 

            fileInfoArr[_this.state.fileInfoArr.length]['urlCode'] =  reader.result;
            fileInfoArr[_this.state.fileInfoArr.length]['title'] =  '';
            fileInfoArr[_this.state.fileInfoArr.length]['description'] =  '';
            fileInfoArr[_this.state.fileInfoArr.length]['isLocal'] =  true;

            let preIndex = this.state.currPicutreIndex;
            _this.setState({
                fileInfoArr : fileInfoArr,
                currPicutreIndex : _this.state.fileInfoArr.length ,
            },()=>{
                document.getElementById(`name${preIndex}`).style.color = "#4A4A4A";
                document.getElementById(`name${_this.state.currPicutreIndex}`).style.color = "#2C7EDC";
                document.querySelector("#file").value = '';
            })
        }.bind(_this)
    }

    switchPicInfo = (item, index) =>{
        document.getElementById(`name${this.state.currPicutreIndex}`).style.color = "#4A4A4A";
        document.getElementById(`name${index}`).style.color = "#2C7EDC";

        this.setState({
            currPicutreIndex : index
        })
    }

    deletePicture = (item, index) =>{
        document.getElementById(`name${index}`).style.color = "#4A4A4A";
        document.getElementById(`name0`).style.color = "#2C7EDC";
        let fileInfoArr =  this.state.fileInfoArr.splice(index, 1);

        this.setState({
            currPicutreIndex : 0,//暂时设置删除后显示第一个
            fileInfoArr : [...this.state.fileInfoArr],
        })
    }

    pictureNameChange = (e)=>{
        let value = e.target.value;
        if(value.length>20){
            danger({'text' : '请限制在20个字符之内'})
            return ;
        }
        this.state.fileInfoArr[this.state.currPicutreIndex]['title'] = value;

        this.setState({
            fileInfoArr : this.state.fileInfoArr
        })
    }
    
    pictureDescribeChange = (e)=>{
        let value = e.target.value;
        if(value.length>50){
            danger({'text' : '请限制在50个字符之内'})
            return ;
        }
        this.state.fileInfoArr[this.state.currPicutreIndex].description = value;

        this.setState({
            fileInfoArr : this.state.fileInfoArr
        })
    }
    mapPicture = () =>{
        let picturesInfo =  this.state.fileInfoArr.map((item, index)=>{
            let uuid = uuid4();
            let filename = `${uuid}---${item.file.name}`;
            item.picture_name = item.isLocal ? filename : item.picture_name;
            return item
        })

        return picturesInfo
    }
    beSureSavePicInfo = () =>{
        let picturesInfo = this.mapPicture.call(this)

        this.props.setProps({
            'examplePictures' : picturesInfo,
            fileInfoArr : this.state.fileInfoArr,
            uploadModal : false,
        })
    }
    
    render(){
        let {
            fileInfoArr,
            currPicutreIndex
        } = this.state;
     
        return (
            <Modal
                    show={this.props.showModal}
                    onHide = {()=>this.props.close(false)}
                    keyboard={false}
                    backdropClosable = {true}
                    centered = {true}
                    backdrop={false}
                    className = {'modal-confirm'}
                >
                    <Modal.Header closeButton = {true} className = {'modal-header'} >
                        <Modal.Title  className = {'modal-header-title'} >{'图片预览'}</Modal.Title>
                    </Modal.Header >
                    <Modal.Body>
                        <div className = {'modal-body-container'}>
                            <div className = {'modal-body-left modal-body-common'}>
                                {this.props.status === "browse" ? null :
                                    <div  className = {'chooseFile'}  size={'md'} class="upload">
                                        <span>选择文件</span>
                                        <input type = 'file' id= 'file' size={5} limit={5} accept="image/*" onChange = {(e)=>{
                                            this.handlePicWithOSS(e)
                                        }}/>
                                    </div>
                                }
                               
                                <div className = {'modal-body-left-list-container'}>
                                    <span className="modal-body-left-list-title">已上传列表</span>
                                    <div className = {'modal-body-left-list'}>
                                        {
                                            fileInfoArr.map((item, index)=>{
                                                return (
                                                    <div  className = {'modal-body-left-list-each'}>
                                                        <span id ={`name${index}`}  className = {'modal-body-left-list-each-name'} onClick={()=>this.switchPicInfo(item, index)}>{item.file && item.file.name}</span>
                                                        {this.props.status === "browse" ? null : <Icon  type="uf-close-c-o"  onClick = {()=>this.deletePicture(item, index)}></Icon>}
                                                    </div>
                                                )
                                            })
                                        }
                                    </div>
                                </div>
                                {this.props.status === "browse" ? null :
                                    <Button
                                        colors="primary"
                                        shape="border"
                                        bordered = {true}
                                        size = {'md'}
                                        className = {'modal-body-left-button'}
                                        onClick = {this.beSureSavePicInfo}
                                    >
                                        确定
                                    </Button>
                                }
                            </div>
                            <div className = {'modal-body-right modal-body-common'}>
                                <div  className = {'modal-body-right-pic-container'}>
                                  
                                    {
                                        fileInfoArr.length > 0?
                                            <img id="image" className = {'modal-body-right-pic'} src={fileInfoArr[currPicutreIndex].urlCode} alt="Picture"/>
                                        : null
                                    }
                                </div>
                                <div className = {'modal-body-right-formcontrol-container'}>
                                    <FormControl
                                        placeholder = '请输入图片名称'
                                        value={fileInfoArr.length > 0 ? fileInfoArr[currPicutreIndex].title :''}
                                        componentClass = {'input'}
                                        onChange={this.pictureNameChange}
                                        disabled = {this.props.status === "browse" ? true : fileInfoArr.length > 0 ? false :true }
                                    />
                                    <FormControl
                                        className="modal-body-right-formcontrol-textaera"
                                        placeholder = '请输入文字表述'
                                        value={fileInfoArr.length > 0 ? fileInfoArr[currPicutreIndex].description : ''}
                                        onChange={this.pictureDescribeChange}
                                        componentClass = {'textarea'}
                                        size = {'xlg'}
                                        disabled = {this.props.status === "browse" ? true : fileInfoArr.length > 0 ? false :true}
                                    />
                                </div>
                            </div>
                        </div>
                    </Modal.Body>
                </Modal>
        )
    }
}
function uploadPicToOSS (additem, callback){
    let _this = this;
    getosssignForPost({param: {clientFlag: 0}, ieStamp :new Date().getTime(),isAjax:1}).then((result)=>{
        let res = result.data.result;
        let promiseArr = [];
        
        _this.state.defaultDataForPic.map((item, index)=>{
            item.map((itemInfo, indexInfo) =>{
                //已经上传过的不管
                if(itemInfo.changeFlag){
                    return;          
                }
                promiseArr.push(new Promise(function (resolve,reject) {

                    let filename = `${res.dir}JCBZ/${itemInfo.picture_name}`;
                    
                    additem.itemtabledata[index].examplePictures[indexInfo].picture_name = filename

                    let formData = new FormData();
                    
                    formData.append("OSSAccessKeyId", res.accessKeyId || '');
                    formData.append("policy", res.policy || '');
                    formData.append("Signature", res.signature || '');
                    formData.append("key", filename);
                    formData.append('file',  itemInfo.file);
                    formData.append('name',  filename);
                  //  formData.append('process', "image/resize,m_fixed");
                    formData.append('success_action_status', '200');
                    delete itemInfo.file;
                    delete itemInfo.urlCode;
                    return axios({
                        url:res.host,
                        method: 'POST',
                        headers: {
                            'Cache-Control': 'no-cache'
                        },
                        ContentType: 'multipart/form-data',
                        data: formData,
                    }).then( (response)=>{
                        console.log(response)
                        if(response.statusText || response.data.resultCode !=='busi_ex'){
                            resolve(filename);
                            return response
                        }else{
                            throw new Error("上传图片出异常,请稍后重试!") 
                        }
                        // getPicUrlByOSS({
                        //     pics:[...filename],
                        //     ieStamp :new Date().getTime(),
                        //     isAjax:1
                        // }).then((res)=>{
                        //     console.log(response,res)
                        //     if(res.data.result){
                        //         let infoObj = []
                        //         data.map((item, index)=>{
                        //             if(isUndefined(tempOSSPictureIndex[index])){//oss路径
                        //                 infoObj[index] = data[index]
                        //             }
                        //         })
                        //         res.data.result.map((item, index)=>{
                        //             let obj = {
                        //                 'title': data[index].title,
                        //                 'description':  data[index].description,
                        //                 'picture_name':  data[index].picture_name,
                        //                 'urlCode' : item,
                        //                 'file': {'name' : data[index].file ? data[index].file.name : data[index].picture_name.split("/")[4].split("---")[1]},//由于uuid有-，所以这里采用---，获取真正的图片名
                                        
                        //             }
                        //             infoObj[tempOSSPictureIndex[index]] = Object.assign(data[index], obj)
                        //         })
                        //         this.setState({
                        //             fileInfoArr : [...infoObj]
                        //         }, ()=>{
                        //             callback&&callback();
                        //         })
                        //     }else{
                        //         danger({'text': res.data.exMsg})
                        //     }
                        // })
                    }).catch((error)=>{
                        _this.setState({
                            showKeepModal: false,
                            showLoading : false,
                        }, ()=>{
                            danger({'text': error.message});
                        });
                    })
                }))
            })
        });
        if(promiseArr.length === 0){//promiseArr空数组，代表没有上传图片的步骤，直接保存
            callback&& callback(additem);
        }else{
            Promise.all(promiseArr).then((imgNameArr)=>{
                callback&& callback(additem);
            },()=>{
                _this.setState({
                    showKeepModal: false,
                    showLoading : false,
                }, ()=>{
                    danger({'text': '上传图片出异常,请稍后重试!'});
                });
            })
        }
       
    })
}
function getPicturesFromOSS (data, tempOSSPictureIndex, callback){
    let pics = [];
    data.map((item, index)=>{
        if(tempOSSPictureIndex[index] !== undefined){//oss路径
            pics[index] = item.picture_name;
        }
    })

    getPicUrlByOSS({
        pics:[...pics],
        ieStamp :new Date().getTime(),
        isAjax:1
    }).then((res)=>{
        if(res.data.result){
            let infoObj = []
            data.map((item, index)=>{
                if(isUndefined(tempOSSPictureIndex[index])){//oss路径
                    infoObj[index] = data[index]
                }
            })
            res.data.result.map((item, index)=>{
                let obj = {
                    'title': data[index].title,
                    'description':  data[index].description,
                    'picture_name':  data[index].picture_name,
                    'urlCode' : item,
                    'file': {'name' : data[index].file ? data[index].file.name : data[index].picture_name.split("/")[4].split("---")[1]},//由于uuid有-，所以这里采用---，获取真正的图片名
                    
                }
                infoObj[tempOSSPictureIndex[index]] = Object.assign(data[index], obj)
            })
            this.setState({
                fileInfoArr : [...infoObj]
            }, ()=>{
                callback&&callback();
            })
        }else{
            danger({'text': res.data.exMsg})
        }
    })
}
export {
    uploadPicToOSS,
    getPicturesFromOSS
}